using BookApi.Dtos;
using Microsoft.AspNetCore.Mvc;
using BookApi.Data;
using Microsoft.EntityFrameworkCore;
using BookApi.Models;

namespace BookApi.Controllers;

[ApiController] //自动模型绑定:从参数中获取请求传入的数据
[Route("api/[controller]")]
public class BookController : ControllerBase
{

    private readonly ApiDbContext _db;

    public BookController(ApiDbContext db)
    {
        _db = db;
    }

    [HttpPost]
    public IActionResult AddBook(BookDto bookDto)
    {
        var book = new Book { BookName = bookDto.BookName, BookAuthor = bookDto.BookAuthor };
        var obj = _db.Book.Add(book).Entity;
        _db.SaveChanges();
        return Ok(new ApiResponse<Book>(obj));
    }

    [HttpGet]
    public IActionResult GetAllBook()
    {
        var books = _db.Book.ToList();
        return Ok(new ApiResponse<List<Book>>(books));
    }

    [HttpPut("{id}")]
    public IActionResult EditBook(int id, BookDto bookDto)
    {
        var book = _db.Book.FirstOrDefault(x => x.Id == id);
        if (book != null)
        {
            book.BookName = bookDto.BookName;
            book.BookAuthor = bookDto.BookAuthor;
            _db.Book.Update(book);
            _db.SaveChanges();
            return Ok(new ApiResponse<BookDto>(bookDto));
        }
        else
        {
            return NotFound(new ApiResponse<string>(404, "查无此书,修改失败"));
        }


    }

    [HttpDelete("{id}")]
    public IActionResult DelBook(int id)
    {
        var book = _db.Book.FirstOrDefault(x => x.Id == id);
        if (book != null)
        {
            _db.Book.Remove(book);
            _db.SaveChanges();
            return Ok(new ApiResponse<Book>(book));
        }
        else
        {
            return NotFound(new ApiResponse<string>(404, "查无此书,删除失败"));
        }

    }

}